package com.mxchip.livestar.ui.settings

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.provider.Settings
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.deeruu.system_help.Ethrenet
import com.mxchip.livestar.R
import com.mxchip.livestar.base.SystemData
import com.mxchip.livestar.base.toast
import com.mxchip.livestar.rx.RxBus
import com.mxchip.livestar.rx.RxConstant
import com.mxchip.livestar.rx.RxSchedulersHelper
import com.mxchip.livestar.update.UpdateInstance
import com.mxchip.livestar.utils.FileLog
import com.mxchip.livestar.utils.SPreference
import com.mxchip.livestar.utils.Utils
import com.videohigh.graham.SampleSDK
import io.reactivex.Observable
import kotlinx.android.synthetic.main.fragment_settings_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.InputStreamReader
import java.text.SimpleDateFormat
import java.util.*


class MainFragment : Fragment() {

    private val formatter = SimpleDateFormat("yyyy-MM-dd")

    private var count = 1

    private val viewModel by activityViewModels<MainViewModel>()
    private val logger: FileLog = FileLog.getLogger(MainFragment::class.java)
    private lateinit var usbDeviceObservable: Observable<Boolean>



    // 使用静态IP还是DHCP
    private val ETHERNET_USE_STATIC_IP = "ethernet_use_static_ip"
    private val updateInstance by lazy {
        UpdateInstance.getInstance(requireContext())
    }

    override fun onDestroyView() {
        super.onDestroyView()
        Log.d(TAG, "onDestroyView: ")
        RxBus.get().unregister(RxConstant.USB_DEVICE_NOTIFY, usbDeviceObservable)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_settings_main, container, false)
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        lifecycleScope.launch {
            val audioDeviceList = loadAudioDevices()
            ext_usb_sound_cb.isChecked = SPreference.isExtUsbAudioDevice()
            view_ext_usb_sound.setOnClickListener { _ ->
                if (!ext_usb_sound_cb.isChecked) {
                    if (audioDeviceList.size > 1) {
                        lifecycleScope.launch {
                            view_ext_usb_sound.isClickable = false
                            changeAudioMuteState()

                            var first = audioDeviceList.first { !it.contains("Sabine") }
                            Ethrenet.setExtUsbSoundMode(first, context)
                            ext_usb_sound_cb.isChecked = true
                            SPreference.setExtUsbAudioDevice(ext_usb_sound_cb.isChecked)
                            changeAudioMuteState()
                            toast("已开启外置音频")
                            view_ext_usb_sound.isClickable = true
                        }

                    } else {
                        toast("请插入外置音频设备")
                        ext_usb_sound_cb.isChecked = false
                    }

                } else {
                    lifecycleScope.launch {
                        view_ext_usb_sound.isClickable = false
                        changeAudioMuteState()
                        ext_usb_sound_cb.isChecked = false
                        SPreference.setExtUsbAudioDevice(ext_usb_sound_cb.isChecked)
                        Ethrenet.setExtUsbSoundMode(audioDeviceList.first { it.contains("Sabine") }, context)
                        changeAudioMuteState()
                        view_ext_usb_sound.isClickable = true
                    }
                    toast("已关闭外置音频")
                }

            }
        }

        val serialNumber = SystemData.deviceId()
        text_sn.text = getString(R.string.equipment_serial_number) + serialNumber

        viewModel.authInfo.observe(viewLifecycleOwner, androidx.lifecycle.Observer {data->
            text_expire.text = getString(R.string.equipment_expiration_date) + ":${formatter.format(data.expireDate ?: 0)}"

            val isAuth = data.isValid

            if (!isAuth) {
                toast(getString(R.string.pay_money))
            }
        })


        view1.setOnClickListener {
            Log.e("MainFragment", "click MainFragment")
            Handler().postDelayed({
                val intent = Intent(Settings.ACTION_SETTINGS)
                startActivity(intent)
            }, 100)
        }

        view2.setOnClickListener {
            findNavController().navigate(R.id.jump_to_wifi)
//            startActivity(Intent(context, WifiActivity::class.java))
        }

        view3.setOnClickListener {
            updateInstance.manualCheck(it.context)
        }

        view_devices.setOnClickListener {
            count++
            if (count %20 == 0) {
                if (system_setting.visibility == View.VISIBLE) {
                    system_setting.visibility = View.GONE
                    view1.visibility = View.GONE
                } else {
                    system_setting.visibility = View.VISIBLE
                    view1.visibility = View.VISIBLE
                }
            }
        }
        var isStaticIp = isStaticIp()
        view_ethernet.setOnClickListener {
            if (isStaticIp) {
                Ethrenet.setMoveIp(requireContext())
                isStaticIp = isStaticIp()
            } else {
                if (!Utils.isEthernet(requireContext())) {
                    toast("请连接有线网络")
                    return@setOnClickListener
                }
                findNavController().navigate(R.id.main_to_ethernet)
            }
        }



        initRxBus()
    }

    private fun isStaticIp(): Boolean {
        var isStaticIp = Ethrenet.isStaticIp(requireContext())
        if (isStaticIp) {
            view_ethernet_tv.text = "启用DHCP"
        } else {
            view_ethernet_tv.text = "静态IP设置"
        }
        return isStaticIp
    }

    @SuppressLint("CheckResult")
    private fun initRxBus() {
        usbDeviceObservable = RxBus.get().register(RxConstant.USB_DEVICE_NOTIFY, Boolean::class.java)
        usbDeviceObservable.compose(RxSchedulersHelper.io_main()).subscribe(::usbDeviceChange) { error ->
            run {
                logger.error(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) +
                        " usbDeviceChange" + error.message)
                error.printStackTrace()
            }
        }
    }

    private fun usbDeviceChange(b: Boolean?) {
        lifecycleScope.launch {
            val audioDeviceList = loadAudioDevices()
            ext_usb_sound_cb.isChecked = audioDeviceList.size > 1
        }
    }

    private suspend fun loadAudioDevices(): List<String> {
        val extAudio = arrayListOf<String>();
        withContext(Dispatchers.IO) {
            extAudio.clear()
            extAudio.addAll(Ethrenet.getAudioDevice())
        }

        return extAudio
    }

    private val TAG = "MainFragmentfff"
    suspend fun changeAudioMuteState() {
        withContext(Dispatchers.IO) {
            var process = Runtime.getRuntime().exec("input keyevent 164")
            val successMsg = StringBuilder()
            val errorMsg = StringBuilder()
            val successResult = BufferedReader(InputStreamReader(process.getInputStream()))
            val errorResult = BufferedReader(InputStreamReader(process.getErrorStream()))
            var s: String? = null
            while (successResult.readLine().also({ s = it }) != null) successMsg.append(s)
            while (errorResult.readLine().also({ s = it }) != null) errorMsg.append(s)
        }

    }

}
